package jaux.tank.service.system.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import jaux.tank.bean.entity.system.EntityExtension;
import jaux.tank.bean.exception.ValidException;
import jaux.tank.bean.vo.EntityQueryCondition;
import jaux.tank.dao.system.EntityExtensionRepository;
import jaux.tank.dao.utils.JpaUtils;
import jaux.tank.service.system.EntityExtensionService;
import jaux.tank.utils.PageUtils;
import jaux.tank.utils.factory.Page;
/**
 * 实体扩展属性服务接口实现
 * @author hxd
 */
@Service
public class EntityExtensionServiceImpl implements EntityExtensionService {

	@Autowired
	EntityExtensionRepository entityExtensionRepo;
	
	@Override
	public Page<EntityExtension> query(List<EntityQueryCondition> list, Page<EntityExtension> defaultPage) {
		org.springframework.data.domain.Page<EntityExtension> opage = entityExtensionRepo.findAll(
				JpaUtils.genPredicateByConditions(list, EntityExtension.class)
				, PageUtils.convertPageToPageable(defaultPage));
		defaultPage.setRecords(opage.getContent());
		defaultPage.setTotal((int)opage.getTotalElements() );
		return defaultPage;
	}
	
	
	
	@Override
	public List<EntityExtension> queryEntityExtensions(String entity, String entityId, String name) {
		return entityExtensionRepo.findAll(JpaUtils.genPredicateByConditions(Arrays.asList(
				new EntityQueryCondition(EntityExtension.Fields.entity, entity)
				,new EntityQueryCondition(EntityExtension.Fields.entityId, entityId)
				,new EntityQueryCondition(EntityExtension.Fields.name, name)
				)
				, EntityExtension.class)
				, Sort.by(EntityExtension.Fields.no));
	}
	@Override
	public Optional<EntityExtension> get(@NotNull String id){
		return entityExtensionRepo.findById(id);
	}
	
	@Override
	public EntityExtension add(@NotNull EntityExtension entityExtension){
		return entityExtensionRepo.save(entityExtension);
	}
	
	
	@Override
	public void remove(@NotNull String id) {
		entityExtensionRepo.deleteById(id);
	}
	
	@Override
	public void removeByEntityId(String entity, String entityId) {
		entityExtensionRepo.deleteByEntityAndEntityId(entity, entityId);
	}
	
	
	@Override
	public EntityExtension update(@NotNull EntityExtension entityExtension){
		if(entityExtension.getId() == null) {
			throw new ValidException("can't update entity without id");
		}
		return entityExtensionRepo.save(entityExtension);
	}
}
